package org.example.commonUtils;

import java.sql.Time;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 辅助类：信号量
 * 功能：限流
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 线程数
        Semaphore semaphore = new Semaphore(2);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                // 获取资源
                try {
                    semaphore.acquire();    // 获得
                    System.out.println(Thread.currentThread().getName() + "得到资源");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "释放资源");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();    // 释放
                }
            }, String.valueOf(i)).start();
        }
    }
}
